<template>
  <view class="daily-time-stats-container">
    <z-paging 
      ref="paging" 
      v-model="dataList" 
      @query="queryList"
      :auto="false"
      :refresher-enabled="true"
      :loading-more-enabled="true"
      :empty-view-text="'暂无数据'"
      class="list-paging"
    >
      <template #top>
        <!-- 页面标题 -->
        <view class="page-header">
          <view class="header-title">每日时段统计</view>
        </view>
        
        <!-- 筛选区域 -->
        <view class="filter-section">
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">开始日期：</text>
              <picker mode="date" :value="filters.startDate" @change="onStartDateChange">
                <view class="date-picker">
                  <text>{{ filters.startDate || '请选择' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
            
            <view class="filter-item">
              <text class="filter-label">时段选择：</text>
              <picker :value="filters.timeSlotIndex" :range="timeSlotOptions" @change="onTimeSlotChange">
                <view class="date-picker">
                  <text>{{ filters.timeSlotIndex >= 0 ? timeSlotOptions[filters.timeSlotIndex] : '全部' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">停车场：</text>
              <picker :value="filters.parkingLotIndex" :range="parkingLotOptions" @change="onParkingLotChange">
                <view class="date-picker">
                  <text>{{ filters.parkingLotIndex >= 0 ? parkingLotOptions[filters.parkingLotIndex] : '全部' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-actions">
            <button class="search-btn" @click="searchData">查询</button>
            <button class="reset-btn" @click="resetFilters">重置</button>
          </view>
        </view>
        
        <!-- 列表表头 -->
        <view class="list-header">
          <text class="list-cell">车流量</text>
          <text class="list-cell">空闲率</text>
          <text class="list-cell">占用率</text>
          <text class="list-cell">平均停车时长</text>
        </view>
      </template>
      
      <!-- 列表内容 -->
      <view v-for="(item, index) in dataList" :key="index" class="list-row" @click="showDetail(item)">
        <text class="list-cell">{{ item.trafficVolume }}</text>
        <text class="list-cell">{{ item.vacancyRate }}%</text>
        <text class="list-cell">{{ item.occupancyRate }}%</text>
        <text class="list-cell">{{ item.avgParkingDuration }}</text>
      </view>
    </z-paging>
    
    <!-- 详情弹窗 -->
    <view class="detail-modal" v-if="showDetailModal">
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">时段详情</text>
          <text class="close-btn" @click="showDetailModal = false">×</text>
        </view>
        
        <view class="detail-body" v-if="currentDetail">
          <view class="detail-item">
            <text class="detail-label">时段：</text>
            <text class="detail-value">{{ currentDetail.timeSlot }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">日期：</text>
            <text class="detail-value">{{ currentDetail.date }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">停车场：</text>
            <text class="detail-value">{{ currentDetail.parkingLot }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">车流量：</text>
            <text class="detail-value">{{ currentDetail.trafficVolume }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">空闲率：</text>
            <text class="detail-value">{{ currentDetail.vacancyRate }}%</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">占用率：</text>
            <text class="detail-value">{{ currentDetail.occupancyRate }}%</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">平均停车时长：</text>
            <text class="detail-value">{{ currentDetail.avgParkingDuration }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">高峰时段：</text>
            <text class="detail-value">{{ currentDetail.peakTime ? '是' : '否' }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">总车位数：</text>
            <text class="detail-value">{{ currentDetail.totalSpaces }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">空闲车位数：</text>
            <text class="detail-value">{{ currentDetail.vacantSpaces }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'

// 筛选条件
const filters = reactive({
  startDate: '',
  timeSlotIndex: -1,
  parkingLotIndex: -1
})

// 停车场选项
const parkingLotOptions = [
  '全部',
  'A区停车场',
  'B区停车场',
  'C区停车场',
  'D区停车场'
]

// 时段选项
const timeSlotOptions = [
  '全部',
  '00:00-02:00',
  '02:00-04:00',
  '04:00-06:00',
  '06:00-08:00',
  '08:00-10:00',
  '10:00-12:00',
  '12:00-14:00',
  '14:00-16:00',
  '16:00-18:00',
  '18:00-20:00',
  '20:00-22:00',
  '22:00-24:00'
]

// 列表数据
const dataList = ref([])
const paging = ref(null)

// 详情弹窗
const showDetailModal = ref(false)
const currentDetail = ref(null)

// 日期选择处理
const onStartDateChange = (e) => {
  filters.startDate = e.detail.value
}

// 时段选择处理
const onTimeSlotChange = (e) => {
  filters.timeSlotIndex = e.detail.value
}

// 停车场选择处理
const onParkingLotChange = (e) => {
  filters.parkingLotIndex = e.detail.value
}

// 查询数据
const searchData = () => {
  if (paging.value) {
    paging.value.reload()
  }
}

// 重置筛选条件
const resetFilters = () => {
  filters.startDate = ''
  filters.timeSlotIndex = -1
  filters.parkingLotIndex = -1
  
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
}

// 查询列表数据
const queryList = (pageNo, pageSize) => {
  // 模拟请求延迟
  setTimeout(() => {
    // 生成模拟数据
    const data = generateMockData(pageNo, pageSize)
    paging.value.complete(data)
  }, 500)
}

// 生成模拟数据
const generateMockData = (pageNo, pageSize) => {
  const data = []
  const startIndex = (pageNo - 1) * pageSize
  
  // 获取时段列表（不包含"全部"选项）
  const timeSlots = timeSlotOptions.slice(1)
  
  // 停车场列表
  const parkingLots = [
    '全部',
    'A区停车场',
    'B区停车场',
    'C区停车场',
    'D区停车场'
  ]
  
  // 生成随机数据
  for (let i = 0; i < pageSize; i++) {
    const index = startIndex + i
    if (index >= timeSlots.length) break // 模拟总数限制
    
    // 选择时段（根据筛选条件）
    let timeSlot
    if (filters.timeSlotIndex > 0) {
      // 如果选择了特定时段，则使用该时段
      timeSlot = timeSlotOptions[filters.timeSlotIndex]
    } else {
      // 否则使用当前索引对应的时段
      timeSlot = timeSlots[index]
    }
    
    // 根据时段设置不同的车流量和占用率
    let trafficVolume, occupancyRate
    
    // 模拟高峰时段（早高峰和晚高峰）
    const isPeakTime = timeSlot === '08:00-10:00' || timeSlot === '18:00-20:00'
    
    if (isPeakTime) {
      // 高峰时段
      trafficVolume = Math.floor(Math.random() * 50) + 150 // 150-200
      occupancyRate = Math.floor(Math.random() * 15) + 85 // 85%-100%
    } else if (timeSlot === '00:00-02:00' || timeSlot === '02:00-04:00' || timeSlot === '04:00-06:00') {
      // 深夜时段
      trafficVolume = Math.floor(Math.random() * 20) + 5 // 5-25
      occupancyRate = Math.floor(Math.random() * 20) + 10 // 10%-30%
    } else {
      // 普通时段
      trafficVolume = Math.floor(Math.random() * 70) + 30 // 30-100
      occupancyRate = Math.floor(Math.random() * 40) + 40 // 40%-80%
    }
    
    // 计算空闲率
    const vacancyRate = 100 - occupancyRate
    
    // 生成平均停车时长（30分钟到4小时）
    const avgMinutes = Math.floor(Math.random() * 210) + 30
    const avgHours = Math.floor(avgMinutes / 60)
    const remainingMinutes = avgMinutes % 60
    const avgParkingDuration = avgHours > 0 
      ? `${avgHours}小时${remainingMinutes > 0 ? remainingMinutes + '分钟' : ''}` 
      : `${remainingMinutes}分钟`
    
    // 生成日期（最近7天内的随机日期）
    const date = new Date()
    date.setDate(date.getDate() - Math.floor(Math.random() * 7))
    const formattedDate = formatDate(date)
    
    // 随机选择停车场
    const selectedParkingLotIndex = filters.parkingLotIndex >= 0 && filters.parkingLotIndex < parkingLots.length 
      ? filters.parkingLotIndex 
      : Math.floor(Math.random() * (parkingLots.length - 1)) + 1 // 排除"全部"选项
    const parkingLot = parkingLots[selectedParkingLotIndex]
    
    // 计算总车位和空闲车位
    const totalSpaces = Math.floor(Math.random() * 100) + 200 // 200-300个车位
    const vacantSpaces = Math.floor(totalSpaces * (vacancyRate / 100))
    
    data.push({
      id: index + 1,
      timeSlot,
      date: formattedDate,
      parkingLot,
      trafficVolume,
      vacancyRate,
      occupancyRate,
      avgParkingDuration,
      peakTime: isPeakTime,
      totalSpaces,
      vacantSpaces
    })
  }
  
  return data
}

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 显示详情
const showDetail = (item) => {
  currentDetail.value = item
  showDetailModal.value = true
}

// 页面加载
onMounted(() => {
  // 设置默认日期（当天）
  const today = new Date()
  
  filters.startDate = formatDate(today)
  
  // 页面挂载时获取数据
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
})
</script>

<style lang="scss" scoped>
.daily-time-stats-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.list-paging {
  flex: 1;
  height: 100%;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
}

.filter-section {
  background: white;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .filter-row {
    display: flex;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .filter-item {
    flex: 1;
    margin-right: 20rpx;
    
    &:last-child {
      margin-right: 0;
    }
    
    &.full-width {
      flex: none;
      width: 100%;
      margin-right: 0;
    }
  }
  
  .filter-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
  }
  
  .date-picker,
  .picker-input {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 10rpx;
    background: #fafafa;
    font-size: 26rpx;
    color: #666;
  }
  
  .filter-actions {
    display: flex;
    gap: 20rpx;
    margin-top: 30rpx;
  }
  
  .search-btn,
  .reset-btn {
    flex: 1;
    padding: 20rpx;
    border-radius: 10rpx;
    font-size: 28rpx;
    border: none;
  }
  
  .search-btn {
    background: #1890FF;
    color: white;
  }
  
  .reset-btn {
    background: #f0f0f0;
    color: #666;
  }
}

.list-header {
  display: flex;
  background: #f0f0f0;
  padding: 20rpx;
  margin: 0 20rpx;
  border-radius: 10rpx 10rpx 0 0;
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
}

.list-row {
  display: flex;
  background: white;
  padding: 20rpx;
  margin: 0 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
  font-size: 26rpx;
  color: #666;
  
  &:last-child {
    border-radius: 0 0 10rpx 10rpx;
    margin-bottom: 20rpx;
  }
}

.list-cell {
  flex: 1;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.detail-content {
  width: 80%;
  max-height: 80%;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #f5f5f5;
  border-bottom: 2rpx solid #e0e0e0;
  
  .detail-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .close-btn {
    font-size: 40rpx;
    color: #999;
    line-height: 1;
  }
}

.detail-body {
  padding: 30rpx;
  overflow-y: auto;
}

.detail-item {
  display: flex;
  margin-bottom: 20rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .detail-label {
    width: 200rpx;
    font-size: 28rpx;
    color: #666;
  }
  
  .detail-value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
}
</style>